package com.example.a2306_shop.fg

import androidx.lifecycle.viewModelScope
import com.example.lib_base.entity.CouponEntity
import com.example.lib_base.entity.IndexEntity
import com.example.lib_base.entity.ProductEntity
import com.example.lib_base.entity.Res
import com.example.lib_base.mvvm.BaseViewModel
import com.example.lib_base.utils.SingleLiveData
import kotlinx.coroutines.launch

class HomeViewModel:BaseViewModel() {
    //请求首页数据
    val indexSuccess = SingleLiveData<Res<IndexEntity>>()
    val indexFail = SingleLiveData<String>()
    fun index(){
        viewModelScope.launch {
            try {
                indexSuccess.postValue(apiService.index())
            } catch (e: Exception) {
                indexFail.postValue(e.message.toString())
            }
        }
    }
    //请求首页商品数据
    val indexProductSuccess = SingleLiveData<Res<ProductEntity>>()
    val indexProductFail = SingleLiveData<String>()
    fun indexProduct(type:Int,limit:Int,page:Int){
        viewModelScope.launch {
            try {
                indexProductSuccess.postValue(apiService.indexProduct(type, limit, page))
            } catch (e: Exception) {
                indexProductFail.postValue(e.message.toString())
            }
        }
    }
    //请求优惠券列表啊
    val couponSuccess = SingleLiveData<Res<CouponEntity>>()
    val couponFail = SingleLiveData<String>()
    fun coupon(limit:String,page:String,type:String){
        viewModelScope.launch {
            try {
                couponSuccess.postValue(apiService.coupon(limit, page, type))
            } catch (e: Exception) {
                couponFail.postValue(e.message.toString())
            }
        }
    }
    //优惠券领取
    val receiveSuccess = SingleLiveData<Res<String?>>()
    val receiveFail = SingleLiveData<String>()
    fun couponReceive(couponId:Int){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map["couponId"] = couponId
                receiveSuccess.postValue(apiService.couponReceive(mapToBody(map)))
            } catch (e: Exception) {
                receiveFail.postValue(e.message.toString())
            }
        }
    }
    val productSuccess = SingleLiveData<Res<ProductEntity>>()
    val productFail = SingleLiveData<String>()
    fun search(keyword:String,limit:Int,page:Int){
        viewModelScope.launch {
            try {
                productSuccess.postValue(apiService.product(keyword, limit, page))
            } catch (e: Exception) {
                productFail.postValue(e.message.toString())
            }
        }
    }
}